#include <avr/io.h>
#include "define.h"

extern uint32_t system_ms;

static bool key_enable = false;
static uint8_t keyboard_key = KEY_NONE;
//int8_t Keyboard::state = 0;
//uint32_t Keyboard::time = 0;

void keyboard_init()
{
    DDRC &= 0XF8;
    PORTC |= 0X07;
    key_enable = true;
}

void keyboard_update()
{
    static int8_t state = 0;
    static uint8_t last_key = 0;
    static uint32_t check_time = 0;
    static uint32_t key_time = 0;
    //uint32_t system_ms = millis();
    if (system_ms < check_time)
        return;

    check_time = system_ms + 20;

    uint8_t cur_key = PINC & 0x07;
    switch (state)
    {
    case 0:	//��ʼ
        if (cur_key != KEY_NONE)
        {
            last_key = cur_key;
            state++;
        }
        break;
    case 1: //�а���
        if (last_key == cur_key)
        {
            keyboard_key = cur_key;
            key_time = system_ms + 1000;
            state++;
        }
        else
        {
            state = 0;
        }
        break;
    case 2: //
        if (cur_key != last_key)
        {
            state = 0;
        }
        else if (system_ms > key_time)
        {
            keyboard_key = cur_key;
            key_time = system_ms + 150;
        }
        break;
    }
}

uint8_t keyboard_get_key()
{
    uint8_t k = 0;
    // if (state == 2)
    {
        k = key_enable? keyboard_key: KEY_NONE;
        keyboard_key = KEY_NONE;
    }
    return k;
}

inline void keyboard_enable()
{
    key_enable = true;
}
inline void keyboard_disable()
{
    key_enable = false;
}
